from flask import Blueprint, render_template, jsonify, request

from tzq.flask_sqlalchemy_postgresql_layui.fspl_models import User

fspl_bp = Blueprint(
    'fspl',
    __name__,
    url_prefix='/fspl',
    template_folder='templates'  # 指定蓝图专属模板目录
)


# 前端页面路由
@fspl_bp.route('/')
def index():
    return render_template('/user_table.html')


# Layui表格数据接口
@fspl_bp.route('/api/users', methods=['GET'])
def get_users():
    # 获取分页参数（Layui自动传递）
    page = int(request.args.get('page', 1))
    limit = int(request.args.get('limit', 10))

    # 获取搜索参数
    search_key = request.args.get('searchKey', '')
    search_value = request.args.get('searchValue', '')

    # 基础查询
    query = User.query

    # 应用搜索条件
    if search_key and search_value:
        if search_key == 'username':
            query = query.filter(User.username.ilike(f'%{search_value}%'))
        elif search_key == 'email':
            query = query.filter(User.email.ilike(f'%{search_value}%'))
        elif search_key == 'role':
            query = query.filter(User.role.ilike(f'%{search_value}%'))

    # 获取排序参数
    sort_field = request.args.get('field', 'id')
    sort_order = request.args.get('order', 'asc')

    # 构建排序
    if hasattr(User, sort_field):
        if sort_order == 'asc':
            order_by = getattr(User, sort_field).asc()
        else:
            order_by = getattr(User, sort_field).desc()
        query = query.order_by(order_by)

    # 分页查询
    pagination = query.paginate(page=page, per_page=limit, error_out=False)

    # 构建Layui要求的JSON格式
    return jsonify({
        'code': 0,
        'msg': '',
        'count': pagination.total,
        'data': [user.to_dict() for user in pagination.items]
    })
